package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Cate;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.domain.ProjectLogDetail;
import com.ruoyi.system.domain.res.projectLog.ProjectLogDay_res;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.ProjectLog;
import com.ruoyi.system.service.IProjectLogService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 竞标项目日志Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-04
 */
@Service
public class ProjectLogServiceImpl implements IProjectLogService {
    @Resource
    private ProjectLogMapper projectLogMapper;
    @Resource
    private ProjectLogDetailMapper projectLogDetailMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private CateMapper cateMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询竞标项目日志
     *
     * @param id 竞标项目日志主键
     * @return 竞标项目日志
     */
    @Override
    public ProjectLog selectProjectLogById(Long id) {
        return projectLogMapper.selectProjectLogById(id);
    }

    /**
     * 查询竞标项目日志列表
     *
     * @param projectLog 竞标项目日志
     * @return 竞标项目日志
     */
    @Override
    public List<ProjectLog> selectProjectLogList(ProjectLog projectLog) {
        if (projectLog.getParams().get("deptId") != null) {
            projectLog.setDeptId(Long.valueOf(String.valueOf(projectLog.getParams().get("deptId"))));
        }
        if (projectLog.getProjectId() != null) {
            projectLog.setDeptId(null);
        }
        List<ProjectLog> projectLogs = projectLogMapper.selectProjectLogList(projectLog);
        projectLogs.forEach(item -> {
            Project project = projectMapper.selectProjectById(item.getProjectId());
            if (project != null) {
                item.setProjectName(project.getTitle());
                item.setEndTime(project.getEndTime());
                if (project.getCateId() != null) {
                    Cate cate = cateMapper.selectCateById(project.getCateId());
                    if (cate != null) {
                        item.setProjectCate(cate.getName());
                    }
                }
            }
            if (item.getDeptId() != null) {
                SysDept company = sysDeptMapper.selectDeptById(item.getDeptId());
                if (company != null) {
                    item.setCompanyName(company.getDeptName());
                    item.setLeader(company.getLeader());
                    item.setPhone(company.getPhone());
                }
            }
        });
        return projectLogs;
    }

    /**
     * 查询中标记录
     */
    @Override
    public List<ProjectLogDay_res> selectProjectLogDay(ProjectLog projectLog) {
        return projectLogMapper.selectProjectLogList(new ProjectLog() {{
            setStatus(2);
            setWeek(projectLog.getWeek());
        }}).stream().map(item -> {
            ProjectLogDay_res res = new ProjectLogDay_res();
            SysDept sysDept = sysDeptMapper.selectDeptById(item.getDeptId());
            if (sysDept != null) {
                res.setDeptName(sysDept.getDeptName());
            }
            Project project = projectMapper.selectProjectById(item.getProjectId());
            if (project != null) {
                Cate cate = cateMapper.selectCateById(project.getCateId());
                if (cate != null) {
                    res.setCateName(cate.getName());
                }
            }
            return res;
        }).collect(Collectors.toList());
    }

    /**
     * 新增竞标项目日志
     *
     * @param projectLog 竞标项目日志
     * @return 结果
     */
    @Override
    public int insertProjectLog(ProjectLog projectLog) {
        projectLog.setCreateTime(DateUtils.getNowDate());

        if (projectLog.getParams().get("details") == null) {
            throw new ServiceException("未竞标");
        }

        //查询该公司该项目有没有投过标
        List<ProjectLog> projectLogs = projectLogMapper.selectProjectLogList(new ProjectLog() {{
            setProjectId(projectLog.getProjectId());
            setDeptId(projectLog.getDeptId());
        }});
        if (projectLogs != null && !projectLogs.isEmpty()) {
            throw new ServiceException("该项目已投过标，不能再次投标");
        }

        List<ProjectLogDetail> details = calAllMonty(projectLog);

        int i = projectLogMapper.insertProjectLog(projectLog);

        insertBatch(projectLog, details);

        return i;
    }

    /**
     * 修改竞标项目日志
     *
     * @param projectLog 竞标项目日志
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProjectLog(ProjectLog projectLog) {
        projectLog.setUpdateTime(DateUtils.getNowDate());

        int i = 0;

        if (projectLog.getParams().get("details") == null) {
            i = projectLogMapper.updateProjectLog(projectLog);
        } else {
            List<ProjectLogDetail> details = calAllMonty(projectLog);

            i = projectLogMapper.updateProjectLog(projectLog);

            projectLogDetailMapper.deleteProjectLogDetailByLogId(projectLog.getId());

            insertBatch(projectLog, details);
        }


        return i;
    }

    /**
     * 计算allMoney
     */
    private List<ProjectLogDetail> calAllMonty(ProjectLog projectLog) {
        List<ProjectLogDetail> details = JSON.parseArray(JSON.toJSONString(projectLog.getParams().get("details")), ProjectLogDetail.class);

        final BigDecimal[] allMoney = {BigDecimal.ZERO};

        if (!details.isEmpty()) {
            details.forEach(item -> {
                allMoney[0] = allMoney[0].add(item.getMoney());
            });
        }

        projectLog.setAllMoney(allMoney[0]);
        return details;
    }

    /**
     * 批量新增details
     */
    private void insertBatch(ProjectLog projectLog, List<ProjectLogDetail> details) {
        details.forEach(item -> {
            item.setLogId(projectLog.getId());
            item.setProjectId(projectLog.getProjectId());
            //计算单价
            item.setPrice(item.getMoney().divide(item.getNum(), 2, RoundingMode.HALF_UP));
        });

        Map<String, Object> params = new HashMap<>(1);
        params.put("details", details);

        projectLogDetailMapper.insertProjectLogDetailBatch(params);
    }

    /**
     * 批量删除竞标项目日志
     *
     * @param ids 需要删除的竞标项目日志主键
     * @return 结果
     */
    @Override
    public int deleteProjectLogByIds(Long[] ids) {
        return projectLogMapper.deleteProjectLogByIds(ids);
    }

    /**
     * 删除竞标项目日志信息
     *
     * @param id 竞标项目日志主键
     * @return 结果
     */
    @Override
    public int deleteProjectLogById(Long id) {
        return projectLogMapper.deleteProjectLogById(id);
    }
}
